'use strict'
const db = uniCloud.database()
const _ = db.command
const MAX_LIMIT = 20

exports.main = async (event, context) => {
  try {
    let body = event
    if (event.body) {
      body = JSON.parse(event.body)
    }

    const { page = 1, pageSize = MAX_LIMIT, date = '' } = body

    const matchCondition = {}
    if (date) {
      matchCondition.date = date
    }

    // 1. 查询分页数据
    const res = await db.collection('appoint_records')
      .where(matchCondition)
      .orderBy('create_time', 'desc')
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .get()

    const totalRes = await db.collection('appoint_records')
      .where(matchCondition)
      .count()

    const records = res.data
    const uidList = [...new Set(records.map(r => r.user))]
    const consultantList = [...new Set(records.map(r => r.consultant))]

    // 2. 查询用户昵称
    const userRes = await db.collection('uni-id-users')
      .where({ _id: _.in(uidList) })
      .field({ _id: true, nickname: true })
      .get()
    const userMap = {}
    userRes.data.forEach(user => {
      userMap[user._id] = user.nickname || '未知用户'
    })

    // 3. 查询咨询师姓名
    const consultantRes = await db.collection('consultants')
      .where({ user_id: _.in(consultantList) })
      .field({ user_id: true, name: true })
      .get()
    const consultantMap = {}
    consultantRes.data.forEach(c => {
      consultantMap[c.user_id] = c.name || '未知咨询师'
    })

    // 4. 合并数据（直接使用 file_path 作为文件URL）
    const finalData = records.map(item => ({
      ...item,
      userNickname: userMap[item.user] || '未知用户',
      consultantName: consultantMap[item.consultant] || '未知咨询师'
    }))

    return {
      success: true,
      result: {
        total: totalRes.total,
        page,
        pageSize,
        data: finalData
      }
    }

  } catch (err) {
    console.error('获取历史咨询记录失败:', err)
    return {
      success: false,
      message: '查询失败',
      error: err.message
    }
  }
}
